<template>
  <div class="max-w-4xl mx-auto px-4 py-8">
    <div class="bg-white/80 backdrop-blur rounded-xl shadow-lg p-6">
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-2xl font-bold text-gray-900">随机点名</h1>
          <p class="text-sm text-gray-600 mt-1">将名字保存到 Redis（7 天）并可通过自定义键加载</p>
        </div>
      </div>

      <div class="mt-6">
        <!-- 大屏显示区 -->
        <div class="w-full h-40 bg-black rounded-md flex items-center justify-center text-white mb-4" :style="{ fontSize: fontSize + 'px' }">
          <div class="truncate px-4">{{ currentName || '—' }}</div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div class="md:col-span-2">
            <label class="text-sm text-gray-600">输入/编辑名单（每行一个名字）</label>
            <textarea v-model="namesText" rows="8" class="w-full mt-2 border rounded p-2 text-sm" placeholder="每行一个名字"></textarea>

            <div class="flex items-center space-x-2 mt-3">
              <button @click="start" :disabled="running" class="primary-button px-4 py-2">开始点名</button>
              <button @click="stop" :disabled="!running" class="border rounded px-4 py-2">停止</button>
              <button @click="saveToRedis" class="bg-blue-600 text-white px-3 py-2 rounded">保存到 Redis（7天）</button>
              <button @click="loadFromRedis" class="border rounded px-3 py-2">从 Redis 加载</button>
            </div>

            <div class="flex items-center space-x-3 mt-3 text-sm text-gray-600">
              <div>速度 (ms)：
                <input v-model.number="speedMs" type="number" class="border rounded px-2 py-1 w-24 ml-2" />
              </div>
              <div>字体大小(px)：
                <input v-model.number="fontSize" type="number" class="border rounded px-2 py-1 w-24 ml-2" />
              </div>
              <label class="inline-flex items-center"><input type="checkbox" v-model="allowRepeat" class="mr-2" />允许重复</label>
            </div>

            <div v-if="message" class="mt-3 text-sm text-green-600">{{ message }}</div>
            <div v-if="error" class="mt-3 text-sm text-red-600">{{ error }}</div>
          </div>

          <div class="bg-white rounded-md p-3 border">
            <div class="text-sm text-gray-500">Redis 键名</div>
            <input v-model="redisKey" class="w-full mt-2 border rounded px-2 py-1 text-sm" placeholder="例如: random:names:class1" />
            <div class="text-sm text-gray-500 mt-3">已加载名单（点击可复制或替换上方）</div>
            <div class="mt-2 max-h-48 overflow-auto text-sm">
              <div v-for="(n, idx) in loadedNames" :key="idx" class="px-2 py-1 border-b hover:bg-gray-50 flex justify-between items-center">
                <div>{{ n }}</div>
                <div>
                  <button @click="copyName(n)" class="text-xs text-blue-600 mr-2">复制</button>
                  <button @click="useName(n)" class="text-xs text-green-600">替换</button>
                </div>
              </div>
              <div v-if="!loadedNames.length" class="text-xs text-gray-400">暂无</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onBeforeUnmount } from 'vue'
declare const useHead: (arg: any) => void
useHead({ title: '随机点名 - 生活工具' })

const namesText = ref('')
const currentName = ref('')
const running = ref(false)
const intervalId = ref<number | null>(null)
const speedMs = ref(100)
const fontSize = ref(80)
const allowRepeat = ref(true)
const redisKey = ref('random:names:default')
const loadedNames = ref<string[]>([])
const message = ref('')
const error = ref('')

const namesList = computed(() => namesText.value.split(/\r?\n/).map(s => s.trim()).filter(Boolean))

function pickRandom() {
  const arr = namesList.value
  if (!arr.length) return null
  const idx = Math.floor(Math.random() * arr.length)
  return arr[idx]
}

function start() {
  if (running.value) return
  const arr = namesList.value
  if (!arr.length) { error.value = '名单为空，请先输入名字'; return }
  error.value = ''
  message.value = ''
  running.value = true
  // 若不允许重复，创建工作数组
  let pool = allowRepeat.value ? null : arr.slice()

  intervalId.value = window.setInterval(() => {
    if (!allowRepeat.value) {
      if (!pool || pool.length === 0) {
        // refill
        pool = arr.slice()
      }
      const i = Math.floor(Math.random() * pool.length)
      currentName.value = pool.splice(i, 1)[0]
    } else {
      currentName.value = arr[Math.floor(Math.random() * arr.length)]
    }
  }, Math.max(10, speedMs.value))
}

function stop() {
  if (intervalId.value !== null) {
    clearInterval(intervalId.value)
    intervalId.value = null
  }
  running.value = false
}

onBeforeUnmount(() => {
  stop()
})

async function saveToRedis() {
  error.value = ''
  message.value = ''
  const key = redisKey.value && redisKey.value.trim()
  if (!key) { error.value = '请填写 Redis 键名'; return }
  const names = namesList.value
  if (!names.length) { error.value = '名单为空，不保存'; return }
  try {
    const res = await fetch('/api/randomnames', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ key, names }) })
    const json = await res.json()
    if (res.ok) {
      message.value = `已保存 ${json.count || names.length} 个名字，TTL ${json.ttl} 秒`
    } else {
      error.value = json?.message || '保存失败'
    }
  } catch (e) {
    error.value = String(e)
  }
}

async function loadFromRedis() {
  error.value = ''
  message.value = ''
  const key = redisKey.value && redisKey.value.trim()
  if (!key) { error.value = '请填写 Redis 键名'; return }
  try {
    const res = await fetch(`/api/randomnames?key=${encodeURIComponent(key)}`)
    const json = await res.json()
    if (res.ok) {
      loadedNames.value = json.names || []
      // 将加载的名字填入编辑框（覆盖）
      namesText.value = (loadedNames.value || []).join('\n')
      message.value = `已加载 ${loadedNames.value.length} 个名字` 
    } else {
      error.value = json?.message || '加载失败'
    }
  } catch (e) {
    error.value = String(e)
  }
}

function copyName(n: string) {
  navigator.clipboard?.writeText(n)
  message.value = '已复制到剪贴板'
}

function useName(n: string) {
  namesText.value = n
  message.value = '已替换编辑框内容为选中名字'
}
</script>

<style scoped>
.primary-button{
  background: linear-gradient(90deg,#4f46e5,#06b6d4);
  color: white;
  padding: 0.5rem 0.75rem;
  border-radius: 0.375rem;
  font-weight: 600;
}
</style>
